﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;

namespace BJoin.Application.WebApi.Authentication
{
    public class BJoinAuthorizationHandler : IAuthenticationHandler
    {    /// <summary>
         /// 认证体系
         /// </summary>
        public AuthenticationScheme Scheme { get; private set; }
        /// <summary>
        /// 当前上下文
        /// </summary>
        protected HttpContext Context { get; private set; }

        public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
        {
            Scheme = scheme;
            Context = context;
            return Task.CompletedTask;
        }
        public Task<AuthenticateResult> AuthenticateAsync()
        {
            //verify token
            var token = Context.Request.Headers["Authorization"];
            //可以在querystring中获取认证信息
            if (string.IsNullOrWhiteSpace(token))
            {
                token = Context.Request.Query["token"];//for file stream and so on
            }
            var env = Context.RequestServices.GetService<IHostEnvironment>();
            if (!env.IsProduction())//非Prod环境
            {                
                if (string.IsNullOrWhiteSpace(token))
                {
                    token = "0921f409e0b9edfa5ba17194e6f88e4f63eb3323"; //Context.Request.Query["token"];
                }
            }
            //
            if (string.IsNullOrWhiteSpace(token) || token.ToString().Length != 40)
                return Task.FromResult(AuthenticateResult.Fail("no bjoin authorization"));
            //check userinfo to identity server
            var claimsIdentity = new ClaimsIdentity(new Claim[] {
                new Claim("clientId", "a9c38cad267e41d3bc20a89f229d363e"),
                new Claim("userToken", token),//0921f409e0b9edfa5ba17194e6f88e4f63eb3323
                new Claim("userId", "2"),
            }, "Authorization");
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            var ticket = new AuthenticationTicket(claimsPrincipal, Scheme.Name);
            return Task.FromResult(AuthenticateResult.Success(ticket));
        }

        public Task ChallengeAsync(AuthenticationProperties properties)
        {
            Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            return Task.CompletedTask;
        }

        public Task ForbidAsync(AuthenticationProperties properties)
        {
            Context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            return Task.CompletedTask;
        }
    }
}
